import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:delivery_application/common/extension.dart';
import 'package:delivery_application/common/globs.dart';
import 'package:delivery_application/common/service_call.dart';
import 'package:delivery_application/common_widget/round_button.dart';
import 'package:delivery_application/common_widget/round_textfield.dart';
import 'package:delivery_application/view/home/home_page.dart';
import 'package:delivery_application/view/login/login_view.dart';
import 'package:delivery_application/view/login/otp_view.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:delivery_application/view/home/start_deliver.dart';

class DetailView extends StatefulWidget {
  const DetailView({super.key});

  @override
  State<DetailView> createState() => _DetailViewState();
}

class _DetailViewState extends State<DetailView> {
  final TextEditingController nameController = TextEditingController();
  final TextEditingController phoneController = TextEditingController();
  final TextEditingController emailController = TextEditingController();
  final TextEditingController passwordController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _loadUserInfo();
  }

  Future<void> _loadUserInfo() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      nameController.text = prefs.getString('userName') ?? '请先登录';
      phoneController.text = prefs.getString('userPhone') ?? '请先登录';
      emailController.text = prefs.getString('userEmail') ?? '请先登录';
      passwordController.text = prefs.getString('userPassword') ?? '******';
    });
  }

  Future<void> _saveUserInfo() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString('userName', nameController.text);
    await prefs.setString('userPhone', phoneController.text);
    await prefs.setString('userEmail', emailController.text);
    await prefs.setString('userPassword', passwordController.text);
    
    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('信息已保存')),
      );
    }
  }
  
  Future<void> _logout() async {
    // 显示确认对话框
    final bool? confirm = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('确认退出'),
        content: Text('确定要退出登录吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(false),
            child: Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.of(context).pop(true),
            child: Text(
              '退出',
              style: TextStyle(color: Colors.red),
            ),
          ),
        ],
      ),
    );

    if (confirm != true) return;
    
    // 清除登录状态
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool('isLoggedIn', false);
    
    // 跳转到StartDeliver页面
    if (mounted) {
      Navigator.pushAndRemoveUntil(
        context,
        MaterialPageRoute(builder: (context) => const StartDeliver()),
        (route) => false,
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: const Color(0xff00AEEE),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        appBar: AppBar(
          title: const Text(
            '我的信息',
            style: TextStyle(
              fontSize: 30,
              fontWeight: FontWeight.bold,
              color: Colors.white,
            ),
          ),
          backgroundColor: Colors.transparent,
          elevation: 0,
          iconTheme: const IconThemeData(color: Colors.white),
          automaticallyImplyLeading: false,
          actions: [
            IconButton(
              icon: Icon(Icons.exit_to_app),
              onPressed: _logout,
              tooltip: '退出登录',
            ),
          ],
        ),
        body: SingleChildScrollView(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            children: [
              const SizedBox(height: 20),
              RoundTextfield(
                hintText: "昵称",
                controller: nameController,
                keyboardType: TextInputType.text,
              ),
              const SizedBox(height: 20),
              RoundTextfield(
                hintText: "Email",
                controller: emailController,
                keyboardType: TextInputType.emailAddress,
              ),
              const SizedBox(height: 20),
              RoundTextfield(
                hintText: "手机",
                controller: phoneController,
                keyboardType: TextInputType.phone,
              ),
              const SizedBox(height: 20),
              RoundTextfield(
                hintText: "设置密码",
                controller: passwordController,
                obscureText: true,
              ),
              const SizedBox(height: 40),
              RoundButton(
                title: "修改信息",
                onPressed: _saveUserInfo,
              ),
            ],
          ),
        ),
      ),
    );
  }
}
